package com.peng.leetcode.list;

import java.util.HashSet;
import java.util.Set;

/**
 * RemoveDuplicateNodes
 *
 * @author: lupeng6
 * @create: 2021/1/11 11:28
 */
public class RemoveDuplicateNodes {

    public static void main(String[] args) {
        ListNode head = BuildListNode.tailInsert(1, 2, 3, 3, 2, 1);
        ListNode listNode = new RemoveDuplicateNodes().removeDuplicateNodes(head);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public ListNode removeDuplicateNodes(ListNode head) {
        Set<Integer> set = new HashSet<>();
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode prev = dummy;
        ListNode curr = dummy.next;
        while (curr != null) {
            if (set.contains(curr.val)) {
                prev.next = curr.next;
            } else {
                set.add(curr.val);
                prev = curr;
            }
            curr = curr.next;
        }
        return dummy.next;
    }
}
